package com.mou.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.mou.constant.DeletedConstant;
import com.mou.constant.MessageConstant;
import com.mou.constant.UserConstant;
import com.mou.context.BaseContext;
import com.mou.dto.PayPasswordDTO;
import com.mou.dto.UserDTO;
import com.mou.dto.UserLoginDTO;
import com.mou.dto.UserPageQueryDTO;
import com.mou.entity.OnlineUser;
import com.mou.entity.Role;
import com.mou.entity.User;
import com.mou.exception.AccountErrorException;
import com.mou.exception.AccountExistException;
import com.mou.exception.AccountLockedException;
import com.mou.exception.PasswordErrorException;
import com.mou.mapper.OnlineUserMapper;
import com.mou.mapper.RoleMapper;
import com.mou.mapper.UserMapper;
import com.mou.result.PageResult;
import com.mou.service.UserService;
import com.mou.utils.Md5Util;
import com.mou.vo.UserProfileVO;
import com.mou.vo.UserVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private  UserMapper userMapper;
    @Autowired
    private OnlineUserMapper onlineUserMapper;
    @Autowired
    private RoleMapper roleMapper;

    @Override
    public User adminLogin(UserLoginDTO userLoginDTO) {

        User u = new User();
        BeanUtils.copyProperties(userLoginDTO,u);
        User user = userMapper.getByUser(u);
        if(user==null){
            throw new AccountExistException(MessageConstant.ACCOUNT_NOT_EXIST);
        }
        if(Objects.equals(user.getStatus(), UserConstant.LOCKED)){
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }
        if(Objects.equals(user.getRoleId(), UserConstant.USER_UNVERIFIED)||Objects.equals(user.getRoleId(), UserConstant.USER_VERIFIED)){
            throw new AccountErrorException(MessageConstant.ROLE_ERROR);
        }
        //输入的password进行md5加密
        String md5Pwd = Md5Util.getMD5String(userLoginDTO.getPassword());
        if(user.getPassword()==null||!user.getPassword().equals(md5Pwd)){
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }
        return user;
    }
    @Override
    public User userLogin(UserLoginDTO userLoginDTO) {

        User u = new User();
        BeanUtils.copyProperties(userLoginDTO,u);
        User user = userMapper.getByUser(u);
        if(user==null){
            throw new AccountExistException(MessageConstant.ACCOUNT_NOT_EXIST);
        }
        if(Objects.equals(user.getStatus(), UserConstant.LOCKED)){
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }
        //输入的password进行md5加密
        String md5Pwd = Md5Util.getMD5String(userLoginDTO.getPassword());
        if(user.getPassword()==null||!user.getPassword().equals(md5Pwd)){
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        return user;
    }

    @Override
    @Transactional
    public void add(UserDTO userDTO) {
        String md5Pwd = Md5Util.getMD5String(userDTO.getPassword());
        User u = new User();
        BeanUtils.copyProperties(userDTO,u);
        User user = userMapper.getByUser(u);
        if(u.getAvatar() == null){
            u.setAvatar("https://wangmou-super.oss-cn-beijing.aliyuncs.com/8a0ab777-22f1-49a8-b33a-d378339e83c6.png");
        }
        u.setPassword(md5Pwd);
        u.setStatus(UserConstant.NORMAL);
        u.setRoleId(UserConstant.USER_UNVERIFIED);
        u.setCreateTime(LocalDateTime.now());
        u.setDeleted(DeletedConstant.DELETED_NO);
        if (user == null){
            userMapper.insert(u);
            User newUser = userMapper.getByUser(u);
            OnlineUser onlineUser = OnlineUser.builder()
                    .userId(newUser.getId())
                    .isOnline(0)
                    .build();
            onlineUserMapper.addOnlineUser(onlineUser);
        }else {
            throw new AccountExistException(MessageConstant.ACCOUNT_EXIST);
        }
    }

    @Override
    public PageResult pageQuery(UserPageQueryDTO userPageQueryDTO) {
        PageHelper.startPage(userPageQueryDTO.getPage(), userPageQueryDTO.getPageSize());
        Page<UserVO> page = userMapper.pageQuery(userPageQueryDTO);
        long total = page.getTotal();
        List<UserVO> tempRecords = page.getResult();

        List<UserVO> records = new ArrayList<>();
        for(UserVO u:tempRecords){
            Role role = roleMapper.selectById(u.getRoleId());
            if (role!=null){
                u.setType(role.getType());
                u.setRoleName(role.getRoleName());
            }else{
                u.setType("danger");
                u.setRoleName("未分配");
            }

            records.add(u);
        }

        return new PageResult(total, records);
    }

    @Override
    public void forgotPassword(UserDTO userDTO) {
        User user = new User();
        BeanUtils.copyProperties(user, userDTO);
        User u = userMapper.getByUser(user);

        if(u==null){
            throw new AccountExistException(MessageConstant.ACCOUNT_NOT_EXIST);
        }
        if(!Objects.equals(u.getUsername(), user.getUsername()) && !Objects.equals(u.getEmail(), user.getEmail())){
            throw new AccountErrorException(MessageConstant.ACCOUNT_ERROR);
        }
        if(u.getRoleId()!=UserConstant.USER_VERIFIED && u.getRoleId()!=UserConstant.USER_UNVERIFIED){
            throw new AccountErrorException(MessageConstant.PERMISSION_DENIED);
        }
        String md5Pwd = Md5Util.getMD5String(user.getPassword());
        user.setPassword(md5Pwd);
        userMapper.forgotPassword(user);
    }

    @Override
    public UserProfileVO getProfileById(Long id) {
        User user = userMapper.selectById(id);
        UserProfileVO profile = new UserProfileVO();
        BeanUtils.copyProperties(user, profile);
        Role role = roleMapper.selectById(user.getRoleId());
        if (role!=null){
            profile.setRoleName(role.getRoleName());
            profile.setType(role.getType());
        }
        return profile;
    }

    @Override
    public void updateProfile(User user) {
        User u = userMapper.selectById(user.getId());
        if(!u.getEmail().equals(user.getEmail()) && !u.getUsername().equals(user.getUsername())){
            Integer count = userMapper.uniqueUser(user);
            if(count>0){
                throw new AccountExistException(MessageConstant.ACCOUNT_EXIST);
            }
        }
        userMapper.updateById(user);
    }

    @Override
    public void updatePayPassword(PayPasswordDTO payPasswordDTO) {
        Integer currentId = BaseContext.getCurrentId();
        User user = userMapper.selectById(currentId);
        String md5PayPwd = Md5Util.getMD5String(payPasswordDTO.getPayPassword());
        if(!Md5Util.checkPassword(payPasswordDTO.getPayPassword(), user.getPayPassword())){
            throw new PasswordErrorException(MessageConstant.PASSWORD_REPEAT);
        }
        if(!user.getPayPassword().equals(md5PayPwd)){
            user.setPayPassword(md5PayPwd);
            userMapper.updateById(user);
        }
    }


}
